using System.Text;
using dotnet.config;
using dotnet.Extensions;
using dotnet.service;
using dotnet.util;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddCustomerCors();

var connectionString = builder.Configuration.GetConnectionString("MySqlConnection");
builder.Services.AddDbContext(connectionString);

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        // validate the token expiration
        ValidateLifetime = true,

        // validate signature
        ValidateIssuerSigningKey = true,

        // need to sure the issuer/audience value here is same with the issuer/audience while token generating
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidIssuer = JWTUtil.Issuer,
        ValidAudience = JWTUtil.Audience,

        //ValidateIssuer = false, // Skip issuer validation
        //ValidateAudience = false, // Skip audience validation

        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JWTUtil.Key)),
        ClockSkew = TimeSpan.FromMinutes(5) // Allow for clock skew

    };

});

builder.Services.AddScoped<UserService>();

builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();
